﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNetStar.TheKing.Domain;
using DotNetStar.TheKing.Models;
using DotNetStar.TheKing.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace DotNetStar.TheKing.Web.Pages
{
    public class IndexModel : PageModel
    {
        public Domain.User CurrentUser { get; set; }

        public PagedCollection<Domain.Content> Contents { get; set; }
        public IEnumerable<Domain.Content> UserHotContents { get; set; }

        /// <summary>
        /// 当前帖子的总数
        /// </summary>
        public int UserContentCount { get; set; }

        private readonly UserService _userService;
        private readonly ContentService _contentService;

        public IndexModel(UserService userService,ContentService contentService)
        {
            _userService = userService;
            _contentService = contentService;
        }

        public async Task<IActionResult> OnGetAsync(long userId)
        {
            this.CurrentUser = await _userService.GetByIdAsync(userId);
            if (this.CurrentUser == null)
            {
                return RedirectToPagePermanent("/Error", new { message = "指定的用户不存在" });
            }
            var condition = new ContentPageQuery(Request.Query["page"].ToString().To(1))
            {
                AuthorUserId = userId,
            };

            if (userId == User.Identity.UserId())
            {
                condition.IncludeSecret = true;
                condition.IncludeStatus = new Infrastructure.ContentStatus[] {
                    Infrastructure.ContentStatus.Auditing,
                    Infrastructure.ContentStatus.Draft,
                    Infrastructure.ContentStatus.Normal
                };
            }


            this.Contents = await _contentService.GetContentsAsync(condition);


            this.UserHotContents = _contentService.GetTopContentQueable(ContentQuery.Default.OnlyContentChannel())
                .Where(m => m.Author.Id == userId).OrderByDescending(m => m.VisitNum).ToList();

            this.UserContentCount = _contentService.GetContentQueable(new ContentQuery { AuthorUserId = userId }).Count();


            return Page();
        }
    }
}